package cn.com.KnowNews.servlet;

import cn.com.KnowNews.entity.News;
import cn.com.KnowNews.service.INewsService;
import cn.com.KnowNews.service.imlp.NewsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "UpdateNewsInfoServlet", urlPatterns = "/UpdateNewsInfo")
@MultipartConfig
public class UpdateNewsInfoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        PrintWriter out = response.getWriter();
        int id = Integer.parseInt(request.getParameter("id"));
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String datetime = request.getParameter("n_datetime");
        String category = request.getParameter("category");
        String main = request.getParameter("main");
        String adder = request.getParameter("addername");

        Part file = request.getPart("picpath");

        News news = new News();
        news.setId(id);
        news.setTitle(title);
        news.setAuthor(author);
        news.setDatetime(datetime);
        news.setCategory(category);
        news.setAdder(adder);
        news.setMain(main);

        File dir = new File("D:\\pic");
        if(!dir.exists()){
            dir.mkdir();
        }

        String oldName =file.getSubmittedFileName();
        news.setPicadr(oldName);
        file.write(dir+"\\"+oldName);

        INewsService newsService = new NewsServiceImpl();
        int result;
        try {
            result= newsService.UpDateNews(news);
            if(result>0){
                request.getSession().setAttribute("news",newsService.showAllNews());
                response.sendRedirect("ShowAllCategory");
            }else{
                out.print("<script>alert('修改失败！')</script>");
                response.setHeader("refresh","1;url="+basePath+"/admin/shownewsadd.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
